﻿'Copyright (c) 2011 Kraigose Studios (Kraig C)

'Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
' to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
' and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

'The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
' FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
' LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
' IN THE SOFTWARE.

Imports FreeImageAPI
Imports System.Drawing

Module modPNG
    ' This processes the PNG for Closing. We have to use indexed PNGs
    Public Function ProcessPNG(ByRef cartf As ArtFile, ByVal index As Integer) As FIBITMAP

        If cartf.XSizes(index) > 0 And cartf.YSizes(index) > 0 Then

            ' This stores the proper color values.
            Dim srcind(256) As RGBQUAD
            For j = 0 To 255
                srcind(j) = New RGBQUAD(Color.FromArgb(PalColor(j).R, PalColor(j).G, PalColor(j).B))
            Next j

            ' Create an indexed image to save
            Dim fmap As FIBITMAP = FreeImage.AllocateEx(cartf.XSizes(index), cartf.YSizes(index), 8, srcind(255), FREE_IMAGE_COLOR_OPTIONS.FICO_RGB, srcind)

            For k = 1 To cartf.YSizes(index)
                For l = 1 To cartf.XSizes(index)
                    Dim indexToUse As Byte = cartf.PicData(index).Pixels(l, k)
                    FreeImage.SetPixelIndex(fmap, l - 1, k - 1, indexToUse)
                Next l
            Next k

            FreeImage.FlipVertical(fmap) ' We have to flip the image before saving it.
            FreeImage.SetTransparentIndex(fmap, 255) ' Set this for easier editing in Photoshop or such

            Return fmap 'Return this so we can save it
        Else
            Return Nothing
        End If
    End Function

    ' PNG Reader.
    Public Sub OpenPNG(ByVal p1 As String, ByRef cartf As ArtFile)
        Dim srcind(256) As RGBQUAD
        For j = 0 To 255
            srcind(j) = New RGBQUAD(Color.FromArgb(PalColor(j).R, PalColor(j).G, PalColor(j).B))
        Next j

        ' Use this to read the new height/width for reallocating the tile
        Dim png As FreeImageBitmap = New FreeImageBitmap(p1)
        Dim tempNewX As Integer = png.Size.Width
        Dim tempNewY As Integer = png.Size.Height
        png.Dispose() ' Dispose of it immediately

        ' Use this to ensure we get the proper index upon returning
        Dim fmap As FIBITMAP = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_PNG, p1, FREE_IMAGE_LOAD_FLAGS.DEFAULT)
        FreeImage.FlipVertical(fmap) ' The image is loaded upside down if we don't do this.

        ' Get the indicies
        With cartf
            ' Reallocate the PicData
            ReDim .PicData(currTileNumInFile).Pixels(tempNewX, tempNewY)
            .XSizes(currTileNumInFile) = tempNewX
            .YSizes(currTileNumInFile) = tempNewY

            Dim pixelIndexFound As Boolean = False  ' Flag for if we find the index early
            Dim currentIndexNum As Byte = 0         ' The current index count.

            ' Make a new PicData
            For i = 1 To .YSizes(currTileNumInFile)
                For j = 1 To .XSizes(currTileNumInFile)
                    ' Escape early if we do find the index. This saves processing time.
                    While pixelIndexFound = False
                        If FreeImage.GetPixelIndex(fmap, j - 1, i - 1, currentIndexNum) Then
                            .PicData(currTileNumInFile).Pixels(j, i) = currentIndexNum
                            pixelIndexFound = True
                            If currentIndexNum = 255 Then
                                currentIndexNum = 0
                            End If
                            currentIndexNum = currentIndexNum + 1
                        End If
                    End While
                    ' Reset counter and flag
                    currentIndexNum = 0
                    pixelIndexFound = False
                Next
            Next
        End With
    End Sub

    Public Sub DumpPNGs(ByVal cArtF As ArtFile, ByRef folder As String)
        Dim i As Integer = 0
        Dim numtiles As Integer = cArtF.LocalEnd - cArtF.LocalStart + 1

        For i = 1 To numtiles
            Dim strFile As String = currTileNumOverall.ToString().PadLeft(4, "0")
            strFile = strFile.ToLower()
            Dim strFullName As String = folder + "\" + "tile" + strFile + ".png"
            Dim tilenumcurrfile As Integer = cArtF.LocalStart + i - 1
            If verbose Then
                Console.WriteLine("Writing png for tile #" + tilenumcurrfile.ToString())
            End If
            Dim fpng As FIBITMAP = ProcessPNG(cArtF, i)
            If fpng <> Nothing Then
                FreeImage.Save(FREE_IMAGE_FORMAT.FIF_PNG, fpng, strFullName, 0)
            End If
            currTileNumOverall += 1
        Next i
    End Sub
End Module
